package com.mall.search.service.imp;

import com.alibaba.dubbo.config.annotation.Service;
import com.mall.pojo.SearchBean;
import com.mall.pojo.SearchResult;
import com.mall.search.service.SearchItemService;
import com.mall.search.service.mappers.ItemsMapper;
import com.mall.search.service.repository.MySolrRepository;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jms.JmsProperties;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.data.solr.core.query.SolrPageRequest;
import org.springframework.data.solr.core.query.result.HighlightEntry;
import org.springframework.data.solr.core.query.result.HighlightPage;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * @author Administrator
 */
@Service(timeout = 1000000)
@Component
@Transactional
public class SearchItemServiceImp implements SearchItemService {

    @Autowired
    private ItemsMapper itemsMapper;

    @Autowired
    private SolrTemplate solrTemplate;

    @Autowired
    private MySolrRepository searchDao;

    @Override
    public void ImportAllItems() {
        List<SearchBean> searchBeans = itemsMapper.selectAllItems();
        for (SearchBean searchBean : searchBeans) {
            solrTemplate.saveBean(searchBean);
        }
        solrTemplate.commit();
    }

    @Override
    public void importItem(long id) {
        SearchBean searchBean = itemsMapper.selectById(id);
        solrTemplate.saveBean(searchBean);
        solrTemplate.commit();
    }

    @Override
    public SearchResult SearchItems(String keyword,int page,int rows) {
        String[] keys = keyword.split(" ");
        List<String> keyWords = Arrays.asList(keys);
        HighlightPage<SearchBean> highlightPage = searchDao.findByTitleContains(
                keyWords, new SolrPageRequest(page, rows));

        //封装查询结果
        SearchResult searchResult = new SearchResult();
        searchResult.setTotalPages(highlightPage.getTotalPages());
        searchResult.setRecordCount(highlightPage.getTotalElements());

        List<HighlightEntry<SearchBean>> highlighted = highlightPage.getHighlighted();

        for (HighlightEntry<SearchBean> searchBeanHighlightEntry : highlighted) {
            SearchBean searchBean = searchBeanHighlightEntry.getEntity();
            searchBean.setTitle(searchBeanHighlightEntry.getHighlights().get(0).getSnipplets().get(0));
        }
        //封装高亮后的SearchBeans
        searchResult.setItemList(highlightPage.getContent());
        return searchResult;
    }
}
